/**
 *  目录
 *
 *  @author  lixiaoxi
 *  @date    2017-09-19
 */

import './index.scss';
import tpl from './index.html';
import globalMessage from 'libs/globalMessage.js';
import {catalogList} from '../../data.js';
import mainObj from '../main/index.js';

let catalogEl = '.catalog-container';
let doc = document;

let catalogObj = {
    catalogInit () {
        doc.querySelector('#catalog').innerHTML = '<h3></h3><p class="tips">听说点左边女生会有目录？～ _ ～</p>';
        $('body').append(tmpl(tpl, {
            list: catalogMake(catalogList, [], 0, 0).join('')
        }));
        requestAnimationFrame(() => {
            $('#catalog').on('click', () => {
                this.toggleCatalog();
            });
            this.eventBind();
        });
    },

    toggleCatalog () {
        if ($(catalogEl).hasClass('ani-left')) {
            $(catalogEl).addClass('ani-left-back');
            $(catalogEl).removeClass('ani-left');
        } else {
            $(catalogEl).removeClass('ani-left-back');
            $(catalogEl).addClass('ani-left');
        }
    },

    eventBind () {
        var self = this;
        $('.catalog-container .cata-item').on('click', function(){
            var type = $(this).data('id');
            mainObj.setPage(type);
            self.toggleCatalog();
        });
    }
};


// 显示 目录 按钮
catalogObj.catalogInit();

function _isArray (obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

function catalogMake (data, res, padding, level) {
    padding = padding + .2;
    level++;
    if (_isArray(data)) {
        for (let i=0; i<data.length; i++) {
            res.push('<p class="cata-item level' + level + '" data-id="' + data[i].type + '" style="padding-left:'+padding+'rem;">' + data[i].name + '</p>');
            if (_isArray(data[i].childs)) {
                catalogMake(data[i].childs, res, padding, level);
            }
        }
    } 
     return res;
}